package endpoint

import (
	"fmt"
	"time"
	"net/http"
	"zxstudy.com/interfaces"
	"zxstudy.com/application"
	"zxstudy.com/infrastructure/persistence"
	"github.com/gin-gonic/gin"
)

type EndPoints struct {
	engine	*gin.Engine
	users 	*interfaces.Users
	groups 	*interfaces.Groups
	cars 	*interfaces.Cars
}

func NewEndPoints(service *persistence.Repositories) *EndPoints {
	return &EndPoints{
		engine: gin.New(),
		users: interfaces.NewUserApplication(application.NewUserApplication(service.User)),
		groups: interfaces.NewGroupApplication(application.NewGroupApplication(service.Group)),
		cars: interfaces.NewCarApplication(application.NewCarApplication(service.Car)),
	}
}

func (e *EndPoints) userEndpoints() {
	e.engine.POST("/user", e.users.Create)
	e.engine.PUT("/user/:id", e.users.Update)
	e.engine.GET("/user/:id", e.users.Get)
	e.engine.GET("/user", e.users.Users)
}

func (e *EndPoints) groupEndpoints() {
	e.engine.POST("/group", e.groups.Create)
	e.engine.GET("/group/:id", e.groups.Get)
	e.engine.GET("/group", e.groups.Groups)
}

func (e *EndPoints) carEndpoints() {
	e.engine.POST("/car", e.cars.Create)
	e.engine.DELETE("/car/:id", e.cars.Delete)
	e.engine.GET("/car/:id", e.cars.Get)
	e.engine.GET("/car", e.cars.Cars)
}
/**
 * 启动服务器
 */
func Run(service *persistence.Repositories) error {
	point := NewEndPoints(service)
	point.userEndpoints()
	point.groupEndpoints()
	point.carEndpoints()

	address := fmt.Sprintf(":%d", 8088)
	s := &http.Server{
		Addr:			address,
		Handler:		point.engine,
		ReadTimeout:	10 * time.Second,
		WriteTimeout:	10 * time.Second,
		MaxHeaderBytes:	1 << 20,
	}
	
	return s.ListenAndServe()
}